Completed
Push — master ( 944ff2...cd9c80 )
by Andres
01:00
created

generate_decay.js ➔ generateReaction   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
c 1
b 0
f 0
nc 4
dl 0
loc 14
rs 8.8571
nop 2
1
/* eslint-env node */
2
/*jslint node: true */
3
'use strict';
4
5
let jsonfile = require('jsonfile');
6
7
let args = process.argv.slice(2);
8
9
let resources = jsonfile.readFileSync(args[0] + '/data/resources.json');
10
let elements = jsonfile.readFileSync(args[0] + '/data/elements.json');
11
12
for (let key in resources) {
13
  let resource = resources[key];
14
  if(resource.type.indexOf('isotope') === -1){
15
    continue;
16
  }
17
  if (resource.decay) {
18
    let ratioSum = 0;
19
    for (let decay in resource.decay.decay_types) {
20
      ratioSum += resource.decay.decay_types[decay].ratio;
21
      resource.decay.decay_types[decay].reaction = generateReaction(key, decay);
22
    }
23
    let difference = 1 - ratioSum;
24
    if (Math.abs(difference) > 1e-6) {
25
      throw new Error('Ratios add up to '.concat(1 - difference, ' for ', key));
26
    }
27
  }
28
}
29
30
function generateReaction(isotope, type) {
31
  switch (type) {
32
  case 'beta-':
33
    return calculateReaction(isotope, 1, 'e-');
34
  case '2beta-':
35
    return calculateReaction(isotope, 2, 'e-');
36
  case 'beta+':
37
    return calculateReaction(isotope, -1, 'e+');
38
  case 'electron_capture':
39
    return calculateReaction(isotope, -1, null);
40
  default:
41
    throw new Error('Unrecognized decay type: ' + type);
42
  }
43
}
44
45
function calculateReaction(isotope, number, particle) {
46
  let element = isotope.replace(/^[0-9]*/, '');
47
  let elementNumber = elements[element].number-1;
48
  let listElements = Object.keys(elements);
49
  let other_element = listElements[elementNumber + number];
50
51
  let isotopeNumber = isotope.replace(element, '');
52
  let product = isotopeNumber + other_element;
53
54
  let energy = resources[isotope].energy - resources[product].energy;
55
56
  let reaction = {};
57
  reaction.reactant = {};
58
  reaction.reactant[isotope] = Math.abs(number);
59
  reaction.product = {};
60
  reaction.product[product] = Math.abs(number);
61
  if(particle){
62
    reaction.product[particle] = Math.abs(number);
63
  }
64
  reaction.product.eV = energy;
65
66
  return reaction;
67
}
68
69
jsonfile.writeFileSync(args[0] + '/data/resources.json', resources, {
70
  spaces: 2
71
});
72